<?php

namespace app\admin\model;

use think\Model;
use think\Db;

class Need extends Model
{

    

    

    // 表名
    protected $name = 'need';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'state_text',
        'category_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk],'remaining'=>$row['num']]);
        });
    }

            public function user()
    {
        return $this->belongsTo('user', 'user_id');
    }

    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '0' => __('Status 0')];
    }

    public function getStateList()
    {
        return ['1' => __('State 1'), '2' => __('State 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStateTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['state']) ? $data['state'] : '');
        $list = $this->getStateList();
        return isset($list[$value]) ? $list[$value] : '';
    }
        public function category()
    {
        return $this->belongsTo('category', 'pid');
    }

    /**

     * 返回类型名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getCategoryTextAttr($value,$data)
    {
        $name = $this->foreach_name($data['pid'],'');
        return $name;
    }

    public function foreach_name($id,$name){
        $exist = Db::name('category')->where('id',$id)->field('id,name,pid')->find();
        if($exist){ 
            $name = $exist['name'].'-'.$name;

            $parent_exist = Db::name('category')->where('id',$exist['pid'])->field('id,pid')->find();

            if($parent_exist['pid']!==0){
                return $this->foreach_name($parent_exist['id'],$name);
            }else{
                $last_name = Db::name('category')->where('id',$parent_exist['id'])->value('name');
                $name = $last_name.'-'.$name;
                return rtrim($name,'-');
            }

        }
    }




}
